package com.mediastory.spsserver.advertising.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.Ostermiller.util.Base64;
import com.mediastory.spsserver.adCategory.dao.AdCategoryDao;
import com.mediastory.spsserver.adCategory.domain.AdCategory;
import com.mediastory.spsserver.adFile.dao.AdFileDao;
import com.mediastory.spsserver.adFile.domain.AdFile;
import com.mediastory.spsserver.advertising.dao.AdvertisingDao;
import com.mediastory.spsserver.advertising.domain.Advertising;
import com.mediastory.spsserver.advertising.service.AdvertisingSvc;

@Service
@Transactional
public class AdvertisingSvcImpl implements AdvertisingSvc {

	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	AdvertisingDao advertisingDao;
	
	@Autowired
	AdFileDao adFileDao;
	
	@Autowired
	AdCategoryDao adCategoryDao;

	public AdvertisingSvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Advertising> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Advertising>) (advertisingDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("advertisingList", (List<Advertising>) (advertisingDao.SelectList(condition)));
		resultMap.put("advertisingListTotalCnt", (Integer) (advertisingDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Advertising findby(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return advertisingDao.select(condition);
	}

	@Override
	public Advertising add(Advertising advertising) throws Exception {
		// TODO Auto-generated method stub
		Advertising result = null;
		List<File> fileList = new Vector<File>();
		
		try {
			result = advertisingDao.insert(advertising);
			
			//파일 업로드
			MultipartFile mFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(advertising.getAdFiles() != null){
				AdFile adFile = new AdFile();
				
				for(int i = 0;i<advertising.getAdFiles().size();i++){
					mFile = advertising.getAdFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
					if(mFile == null || mFile.getSize() == 0){
						continue;
					}
					
					fileType = advertising.getAdFileTypes()[i];
					fileData = advertising.getAdFileDatas()[i];
					fileSize = mFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(advertising.getName(), "UTF-8")+Long.toString(time)));
					//업로드 경로
					String uploadDir = messages.getMessage("file.advertising.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.advertising.viewUrl");
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("adImg")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_adImg."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else{
						continue;
					}
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					mFile.transferTo(file);
					
					fileList.add(file);
					
					//파일 등록
					adFile.setAdIdx(result.getIdx());
					adFile.setCreatedId(result.getCreatedId());
					adFile.setCreatedIp(result.getCreatedIp());
					adFile.setFileUrl(url);
					adFile.setFileSize(fileSize);
					adFile.setFileType(fileType);
					adFile.setFileData(fileData);
					adFileDao.insert(adFile);
				}
			}

			//disp order 등록
			if(advertising.getAdCategoryIdx() != null){
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("adIdx", result.getIdx());
				for (Integer adCategoryIdx : advertising.getAdCategoryIdx()) {
					condition.put("adCategoryIdx", adCategoryIdx);
					adCategoryDao.insertDispOrder(condition);
				}
			}	
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return result;
	}

	@Override
	public Advertising modify(Advertising advertising) throws Exception {
		// TODO Auto-generated method stub
		List<File> fileList = new Vector<File>();
		
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("adIdx", advertising.getIdx());
			
			List<AdCategory> adCategoryList = adCategoryDao.SelectList(condition);
			for(AdCategory adCategory : adCategoryList){
				condition.put("adCategoryIdx", adCategory.getIdx());
				if(adCategory.getAdIdx() != null){
					boolean chkFlag = false;
					if(advertising.getAdCategoryIdx() != null){
						for (Integer adCategoryIdx : advertising.getAdCategoryIdx()) {
							if(adCategory.getIdx() == adCategoryIdx){
								chkFlag = true;
								break;
							}
						}
					}
					if(! chkFlag){
						adCategoryDao.deleteDispOrder(condition);
					}
				}else if(advertising.getAdCategoryIdx() != null){
					boolean chkFlag = false;
					
					for (Integer adCategoryIdx : advertising.getAdCategoryIdx()) {
						if(adCategory.getIdx() == adCategoryIdx){
							chkFlag = true;
							break;
						}
					}
					if(chkFlag){
						adCategoryDao.insertDispOrder(condition);
					}
				}
			}
			
			//파일 업로드
			condition = new HashMap<String, Object>();
			condition.put("modifiedId", advertising.getModifiedId());
			condition.put("modifiedIp", advertising.getModifiedIp());
			condition.put("adIdx", advertising.getIdx());
			
			MultipartFile mFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(advertising.getAdFiles() != null){
				AdFile adFile = new AdFile();
				
				for(int i = 0;i<advertising.getAdFiles().size();i++){
					mFile = advertising.getAdFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
	 				if(mFile == null || mFile.getSize() == 0){
						continue;
					}
					
					fileType = advertising.getAdFileTypes()[i];
					fileData = advertising.getAdFileDatas()[i];
					fileSize = mFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(advertising.getName(), "UTF-8")+Long.toString(time)));
					//업로드 경로
					String uploadDir = messages.getMessage("file.advertising.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.advertising.viewUrl");
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("adImg")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_adImg."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
						
						//기존 등록된 파일 데이터 삭제
						condition.put("fileType", "adImg");
						adFileDao.delete(condition);
					}else{
						continue;
					}
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					mFile.transferTo(file);
					
					fileList.add(file);
					
					//파일 등록
					adFile.setAdIdx(advertising.getIdx());
					adFile.setCreatedId(advertising.getModifiedId());
					adFile.setCreatedIp(advertising.getModifiedIp());
					adFile.setFileUrl(url);
					adFile.setFileSize(fileSize);
					adFile.setFileType(fileType);
					adFile.setFileData(fileData);
					adFileDao.insert(adFile);
				}
			}
			
			//광고 이미지 수정
			AdFile adFile = new AdFile();
			fileType = advertising.getAdFileTypes()[0];
			fileData = advertising.getAdFileDatas()[0];
			adFile.setIdx(advertising.getAdFileIdx()[0]);
			adFile.setFileType(fileType);
			adFile.setFileData(fileData);
			adFile.setAdIdx(advertising.getIdx());
			adFile.setModifiedId(advertising.getModifiedId());
			adFile.setModifiedIp(advertising.getModifiedIp());
			adFileDao.update(adFile);

			advertising = advertisingDao.update(advertising);
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return advertising;
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return advertisingDao.delete(condition);
	}

	@Override
	public String findbyChkDupl(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub

		String result = "true";
		Integer cnt = (Integer) (advertisingDao.SelectListTotalCnt(condition));
		if(cnt != null && cnt == 0){
			result = "false";
		}
		
		return result;
	}

}
